<template>
  <div class="container_edit">
    <div class="header">
      <p>新增/编辑商品</p>
      <el-button
        type="primary"
        @click="back"
      >返回</el-button>
    </div>
    <div class="main">
      <el-form
        :model="user"
        :rules="rules"
        ref="user"
        label-width="150px"
        class=""
      >
        <el-form-item
          label="商品名称："
          prop="productName"
        >
          <el-input
            v-model="user.productName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品类别："
          prop="classify"
        >
          <el-select
            filterable
            v-model='user.classify'
            placeholder='-请选择-'
            @change="classifyChange"
          >
            <el-option
              v-for="item in statusList1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="经销商进货价："
          prop="productCode"
        >
          <el-input
            v-model="user.productCode"
            placeholder="请输入"
          ></el-input>
          <span style="margin-left:20px">元/套袋</span>
        </el-form-item>
        <el-form-item
          label="终端零售价："
          prop="productCode"
        >
          <el-input
            v-model="user.productCode"
            placeholder="请输入"
          ></el-input>
          <span style="margin-left:20px">元/套袋</span>
        </el-form-item>
         <el-form-item
          label="规格："
          prop="productCode"
        >
          <el-input
            v-model="user.productCode"
            placeholder="请输入"
          ></el-input>
          <span style="margin-left:20px">套袋/件</span>
        </el-form-item>
        <el-form-item
          label="是否上架："
          prop="category"
        >
          <el-select
            filterable
            v-model='user.category'
            placeholder='-请选择-'
          >
            <el-option
              v-for="item in categoryArr"
              :key="item.id"
              :label="item.categoryName"
              :value="item.categoryName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否包邮："
          prop="category"
        >
          <el-select
            filterable
            v-model='user.category'
            placeholder='-请选择-'
          >
            <el-option
              v-for="item in categoryArr"
              :key="item.id"
              :label="item.categoryName"
              :value="item.categoryName"
            ></el-option>
          </el-select>
          <el-input
            v-model="user.productCode"
            placeholder="请输入邮费"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品轮播图："
          prop="pictureFileKey"
        >
          <el-upload
            class="normal-uploader"
            list-type="picture-card"
            :action="upLoadUrl"
            :before-upload="beforeAvatarUpload"
            :file-list='fileShowList'
            :on-remove="handleRemove"
            multiple
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="商品详情："
          prop="productDetail"
        >
          <bg-editor
            :minHeight="300"
            :uploadUrl="upLoadUrl"
            :content="user.productDetail"
            @editorData='editorInfo'
          >
          </bg-editor>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSave('user')"
          >保存</el-button>
          <el-button @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
let CONSTANT = require("../../constant/constant.js");
let common = require("../../common.js");
export default {
  data() {
    return {
      upLoadUrl: "",
      imageUrl: "",
      fileShowList: [],
      uploadState: false,
      wayArr: [],
      user: {
        category: "",
        city: "",
        classify: "",
        discountPrice: "",
        distributionMode: "",
        freight: "",
        id: "",
        coverFileKey: "",
        pictureFileKey: "",
        productCode: "",
        productDetail: "",
        productName: "",
        productPrice: "",
        specifications: [
          {
            id: "",
            inventory: "",
            productId: "",
            specificationName: ""
          }
        ],
        style: "",
        way: ""
      },
      statusList: [
        { label: "现货", value: "spot_goods" },
        { label: "预售", value: "presell" }
      ],
      statusList1: [
        { label: "家具", value: "furniture" },
        { label: "家居", value: "house_and_home" }
      ],
      statusList2: ["商家配送", "到店自取"],
      statusList3: [
        { label: "武汉", value: "101" },
        { label: "杭州", value: "100" }
      ],
      categoryArr: [],
      currentPage: "",
      styleArr: [],
      rules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        productCode: [
          { required: true, message: "请输入商品编码", trigger: "blur" }
        ],
        classify: [{ required: true, message: "请选择分类", trigger: "blur" }],
        category: [{ required: true, message: "请选择类目", trigger: "blur" }],
        style: [{ required: true, message: "请选择风格", trigger: "blur" }],
        way: [{ required: true, message: "请选择销售方式", trigger: "blur" }],
        city: [{ required: true, message: "请选择城市", trigger: "blur" }],
        productPrice: [
          { required: true, message: "请输入价格", trigger: "blur" }
        ],
        discountPrice: [
          { required: true, message: "请输入折扣价", trigger: "blur" }
        ],
        distributionMode: [
          { required: true, message: "请选择配送支持：", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.id = this.$router.currentRoute.query.id;
    let sessionId = sessionStorage.getItem("sessionId");
    this.currentPage = this.$router.currentRoute.query.pageIndex
      ? this.$router.currentRoute.query.pageIndex
      : 1;
    this.upLoadUrl =
      CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS + "?sessionId=" + sessionId;
    if (this.id) {
      // this.getInfo();
    }
  },
  components: {
    "bg-editor": () => import("../common/bg-editor.vue")
  },
  methods: {
    addTable() {
      this.user.specifications.push({
        id: "",
        inventory: "",
        productId: "",
        specificationName: ""
      });
    },
    deleteTable(num) {
      this.user.specifications.splice(num, 1);
    },
    wayChange() {
      if (this.wayArr.length == 2) {
        this.user.distributionMode = "all_support";
      } else {
        this.user.distributionMode =
          this.wayArr[0] == "商家配送" ? "merchant" : "invite";
      }
    },
    classifyChange() {
      this.user.category = "";
      this.user.style = "";
      this.getList();
      this.getList1();
    },
    getList() {
      let url = CONSTANT.URL.LIST.FINDCATEGORY;
      let data = {
        categoryType: "category",
        classify: this.user.classify
      };
      this.loading = true;
      common.requestAjax(url, JSON.stringify(data), null, res => {
        this.loading = false;
        let data = res.data;
        this.categoryArr = data.bussData;
      });
    },
    getList1() {
      let url = CONSTANT.URL.LIST.FINDCATEGORY;
      let data = {
        categoryType: "style",
        classify: this.user.classify
      };
      this.loading = true;
      common.requestAjax(url, JSON.stringify(data), null, res => {
        this.loading = false;
        let data = res.data;
        this.styleArr = data.bussData;
      });
    },
    handleRemove(file, fileList) {
      // 图片上传
      let deleteUrl = file.url;
      let list = this.fileShowList;
      list.forEach(function(item, index) {
        if (item.url == deleteUrl) {
          list.splice(index, 1);
        }
      });
      this.fileShowList = list;
    },
    handleRemove1(file, fileList) {
      this.user.coverFileKey = "";
      this.imageUrl = "";
    },
    getInfo: function() {
      let url = CONSTANT.URL.LIST.FINDPRODUCTBYID;
      common.requestAjax(url, null, { id: this.id }, res => {
        if (res.status == 200) {
          let data = res.data.bussData;
          this.user = {
            category: data.category,
            city: data.city,
            classify: data.classify,
            discountPrice: data.discountPrice,
            distributionMode: data.distributionMode,
            freight: data.freight,
            id: data.id,
            coverFileKey: data.coverFileKey,
            pictureFileKey: data.pictureFileKey,
            productCode: data.productCode,
            productDetail: data.productDetail,
            productName: data.productName,
            productPrice: data.productPrice,
            specifications: data.specifications,
            style: data.style,
            way: data.way
          };
          let arr = data.pictureFileKey.split(",");
          data.pictureUrl.map((item, index) => {
            this.fileShowList.push({
              url: item,
              fileKey: arr[index]
            });
          });
          this.imageUrl = data.coverUrl;
          if (data.distributionMode == "all_support") {
            this.wayArr = ["商家配送", "到店自取"];
          } else {
            this.wayArr =
              data.distributionMode == "merchant" ? ["商家配送"] : ["到店自取"];
          }
        }
      });
    },
    editorInfo(val) {
      this.user.productDetail = val;
    },
    handleSave: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let arr = [];
          this.fileShowList.map(item => {
            arr.push(item.fileKey);
          });
          this.user.pictureFileKey = arr.join(",");
          let url = CONSTANT.URL.LIST.SAVEPRODUCT;
          common.requestAjax(url, JSON.stringify(this.user), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "保存成功！"
              });
              this.$router.replace({
                path: "/goodList",
                query: { pageIndex: this.currentPage }
              });
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    beforeAvatarUpload(file) {
      console.log(file);
      let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
      let param = {
        suffix: file.name.split(".")[1], // 文件后缀  png
        contentType: file.type // 文件类型  image/png
      };
      common.requestAjax(url, param, null, res => {
        this.upLoadUrl = res.data.bussData.uploadUrl;
        this.user.pictureFileKey = res.data.bussData.fileKey;
        let downloadUrl = res.data.bussData.downloadUrl;
        common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
          this.fileShowList.push({
            url: res.data.bussData.downloadUrl,
            fileKey: res.data.bussData.fileKey
          });
        });
      });
    },
    beforeAvatarUpload1(file) {
      console.log(file);
      let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
      let param = {
        suffix: file.name.split(".")[1], // 文件后缀  png
        contentType: file.type // 文件类型  image/png
      };
      common.requestAjax(url, param, null, res => {
        this.upLoadUrl = res.data.bussData.uploadUrl;
        this.user.coverFileKey = res.data.bussData.fileKey;
        let downloadUrl = res.data.bussData.downloadUrl;
        common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
          this.imageUrl = downloadUrl;
        });
      });
    },
    back() {
      this.$router.push({
        path: "/goodList",
        query: { currentPage: this.currentPage }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.table-content {
  width: 500px;
  .table-item {
    position: relative;
    border: 1px solid #dcdfe6;
    i {
      position: absolute;
      right: -30px;
      top: 20px;
      cursor: pointer;
      font-size: 16px;
    }
    &:first-child {
      background-color: #409eff;
      color: #fff;
      border-right: 0px solid #dcdfe6;
      .table-list {
        padding: 0;
      }
    }

    .table-list {
      flex: 2;
      text-align: center;
      padding: 5px 0;
      .el-input {
        height: 70% !important;
        width: 90%;
      }
      &:first-child {
        flex: 3;
        border-right: 1px solid #dcdfe6;
      }
    }
  }
}
</style>
